package org.wu.framework.core.utils;


import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.wu.framework.core.NormalUsedString;
import org.wu.framework.core.exception.RuntimeExceptionFactory;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * socket 发送工具
 */

@Slf4j
public class SocketSendUtil {

    /**
     *
     * @param ip   请求的ip
     * @param port 请求端口
     * @param curl  请求信息
     *              <p>
     *              curl 'https://www.zhipin.com/wapi/zpgeek/pc/recommend/job/list.json?page=1&pageSize=15&city=101210100&encryptExpectId=&mixExpectType=&expectInfo=&jobType=&salary=&experience=&degree=&industry=&scale=&_=1752236680609' \
     *   -H 'accept: application/json, text/plain, *\/*' \
     *   -H 'accept-language:zh-CN,zh;q=0.9' \
     *   -b 'lastCity=101210100;__zp_seo_uuid__=c127a66a-c32b-48c8-9922-38e68f276ceb;__l=r=https%3A%2F%2Fwww.google.com%2F&l=%2F&s=1;__g=-;Hm_lvt_194df3105ad7148dcf2b98a91b5e727a=1752227729;HMACCOUNT=E12FA8317F1FBEC2;wt2=DcZwnO_EigAmnmKo9ncVkLjm_VmGSQbYrNCtyZSlL6OQAcvq5C35SkpTxRDYFH8U7RrhTb80BENIxGag1RXDjHw~~;wbg=0;zp_at=p2KdHC6P5beWE8bSoHrWbW1ap7pNQcti2oo78rbNc6M~;ab_guid=c71d5784-aec0-4eb6-adea-9c538b7e331b;Hm_lpvt_194df3105ad7148dcf2b98a91b5e727a=1752230985;bst=V2Qt0mEOf-21lgXdJszRQdKC2w7DrTzQ~~|Qt0mEOf-21lgXdJszRQdKC2w7DvSzQ~~;__c=1752227729;__a=78645062.1752227729..1752227729.13.1.13.13;__zp_stoken__=771dfOTbDlsK9wpvCtD0vDwkJCQAwIDA2Kio4OSIyPDw5Njw%2BPjk2NBwwKcO7wrzCsDZJW8ONJzkiNjw1OTk4PDw6EjYwxLrCsDY5KcKRwrnCvTlMVcOABMK%2Fwr0RPcK5B8O0wr0EwoPCsxFowrkjJCzCvzAwOz3DgcK3wpDCusOBwr7CkMK9H8K%2Bwp3CvTAzPWUqNA4AX1k0M0hKVwJFVE1hWFELQktLJT0wNjk9wrfDvSw3CQ8PBgYJDw8GBgYMDAoKBgwMCQkDDQ0AAC48wpXCsMO8wo9ZwpDDosSWwpDCrsOqQ8KXwpLCm0nDtFPCrcK0w7vCtcKpwrvCtlHCo0rCr1vCiF%2FCocK1wpBkV15uRk97wrZvV8K%2FV2PCs1bDgWkKWwIEETQLXF3DgA%3D%3D' \
     *   -H 'priority:u=1,i' \
     *   -H 'referer:https://www.zhipin.com/web/geek/jobs?city=101210100' \
     *-H 'sec-ch-ua: "Not)A;Brand";v="8", "Chromium";v="138", "Google Chrome";v="138"' \
     *-H 'sec-ch-ua-mobile: ?0' \
     *-H 'sec-ch-ua-platform: "macOS"' \
     *-H 'sec-fetch-dest: empty' \
     *-H 'sec-fetch-mode: cors' \
     *-H 'sec-fetch-site: same-origin' \
     *-H 'token: KhReS6dNmtMj1us' \
     *-H 'traceid: F-71e5a1svdUstoQK9' \
     *-H 'user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36' \
     *-H 'x-requested-with: XMLHttpRequest' \
     *-H 'zp_token: V2Qt0mEOf-21lgXdJszRQdKC2w7DrTzQ~~|Qt0mEOf-21lgXdJszRQdKC2w7DvSzQ~~'
     *              </p>
     * @return 返回请求信息
     */
    /**
     *
     */
    public static SocketHttpResponse sendCurlReceive(String ip, int port, String curl) {
        if (ObjectUtils.isNotEmpty(curl)) {

            StringBuilder builder = new StringBuilder();

            if (curl.startsWith("curl -X")) {
                curl = curl.replaceFirst("curl -X", "");
            }
            if (curl.startsWith("curl")) {
                curl = curl.replaceFirst(NormalUsedString.SPACE, NormalUsedString.EMPTY);
                curl = curl.replaceFirst(NormalUsedString.SINGLE_QUOTE, NormalUsedString.EMPTY);

                curl = curl.replaceFirst("curl", "GET" + NormalUsedString.NEWLINE);
            }
            String[] curlSplitList = curl.split(NormalUsedString.NEWLINE);
            for (String line : curlSplitList) {
                // 去除空格
                line = line.replaceAll(NormalUsedString.SPACE, NormalUsedString.EMPTY);
                if (line.startsWith("-b")) {
                    continue;
                }
                if (line.startsWith("-H")) {
                    line = line.replaceFirst("-H", "");
                }
                // 去除最后的\
                if (line.lastIndexOf("\\") > 0) {
                    line = line.substring(0, line.length() - 1);
                }
                // 去除 ‘
                if (line.startsWith(NormalUsedString.SINGLE_QUOTE) && line.endsWith(NormalUsedString.SINGLE_QUOTE)) {
                    line = line.substring(1, line.length() - 1);
                }
                // : 中间需要由间隔
                if (!line.startsWith("http")) {
                    line = line.replaceAll(NormalUsedString.COLON, NormalUsedString.COLON + NormalUsedString.SPACE);
                }
                line += NormalUsedString.NEWLINE;
                builder.append(line);
            }


            System.out.println("send http with body:" + builder);
            return sendAndReceive(ip, port, builder.toString().getBytes(StandardCharsets.UTF_8));
        }
        RuntimeExceptionFactory.of("解析curl错误");
        return null;

    }

    /**
     * 使用tcp发送请求数据
     *
     * @param ip   请求的ip
     * @param port 请求端口
     * @param msg  请求信息
     * @return 返回请求信息
     */
    public static SocketHttpResponse sendAndReceive(String ip, int port, byte[] msg) {
        //这里比较重要，需要给请求信息添加终止符，否则服务端会在解析数据时，一直等待
        StringBuilder requestBody = new StringBuilder();
        SocketHttpResponse socketHttpResponse = new DefaultSocketHttpResponse();
        //开启一个链接，需要指定地址和端口
        try (Socket client = new Socket(ip, port)) {
            //向输出流中写入数据，传向服务端
            OutputStream out = client.getOutputStream();
            out.write(msg);

            //从输入流中解析数据，输入流来自服务端的响应
            InputStream in = client.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));

            // 读取请求头
            String line;
            StringBuilder requestHeader = new StringBuilder();
            while ((line = reader.readLine()) != null && !line.isEmpty()) {
                requestHeader.append(line).append("\r\n");
            }

            socketHttpResponse.setHeader(requestHeader.toString());
            // 输出请求头
            //            System.out.println("请求头：\n" + requestHeader.toString());

            // 读取请求体
            if (reader.ready()) {
                char[] buffer = new char[1024];
                int bytesRead;
                while ((bytesRead = reader.read(buffer)) != -1) {
                    requestBody.append(buffer, 0, bytesRead);
                }
            }
            // 输出请求体
            // System.out.println("请求体：\n" + requestBody.toString());
            socketHttpResponse.setBody(requestBody.toString());
            // 获取状态代码
            StringBuilder response = new StringBuilder();
            response.append(requestHeader);
            response.append(requestBody);
            int statusCode = getStatusCode(response.toString());
            socketHttpResponse.setHttpStatus(statusCode);
            //System.out.println("Status Code: " + statusCode);
        } catch (Exception e) {
            e.printStackTrace();
            socketHttpResponse.setHttpStatus(500);
            socketHttpResponse.setBody(e.getMessage());
            return socketHttpResponse;
        } finally {

        }
        return socketHttpResponse;
    }

    /**
     * 获取状态代码
     *
     * @param response tcp 报文结果
     * @return int 状态
     */
    private static int getStatusCode(String response) {
        String[] lines = response.split("\r\n");

        if (lines.length > 0) {
            String[] statusLineParts = lines[0].split(" ");

            if (statusLineParts.length > 1) {
                return Integer.parseInt(statusLineParts[1]);
            }
        }

        return -1; // 如果解析失败，返回一个特殊值表示错误
    }

    public static void main(String[] args) {
        java.lang.String s = "POST http://tenant-cloud-gateway:7777/management-cloud-gateway-forward/management-lms-online-retailers-provide/api/lms/online/service/salesOrder/getSalesDpOrder?customerId=2740 HTTP/1.0\n" +
                "feign_header_name: feign_header_name\n" +
                "feign_header_time_name: 563498334-\n" +
                "Accept: */*\n" +
                "User-Agent: Java/17.0.7\n" +
                "Content-type: application/x-www-form-urlencoded\n" +
                "X-Forwarded-For: 10.244.2.204,10.244.2.204\n" +
                "X-Forwarded-Proto: http,http\n" +
                "X-Forwarded-Prefix: /under-cloud-central-gateway\n" +
                "X-Forwarded-Port: 7777,7777\n" +
                "X-Forwarded-Host: tenant-cloud-gateway:7777,tenant-cloud-gateway:7777\n" +
                "host: 10.244.1.225:7002\n" +
                "request_id: 6bee4459-854082\n" +
                "request_times: 2\n" +
                "tenant_id: 2561\n" +
                "version: middleground-2.5.8-SNAPSHOT\n" +
                "6bee4459-854082: true\n" +
                "Forwarded: proto=http;host=\"tenant-cloud-gateway:7777\";for=\"10.244.2.204:47368\"\n" +
                "Forwarded: proto=http;host=\"10.244.1.225:7002\";for=\"10.244.2.204:47368\"\n" +
                "content-length: 0\n" +
                "\n" +
                "is_off_line: true\n";
        SocketHttpResponse result = sendAndReceive("ly.laihui.cn", 30570, s.getBytes());
        System.out.println(result);

        String curl = "curl 'https://www.zhipin.com/wapi/zpgeek/pc/recommend/job/list.json?page=1&pageSize=15&city=101210100&encryptExpectId=&mixExpectType=&expectInfo=&jobType=&salary=&experience=&degree=&industry=&scale=&_=1752236680609' \\\n" +
                "  -H 'accept: application/json, text/plain, */*' \\\n" +
                "  -H 'accept-language: zh-CN,zh;q=0.9' \\\n" +
                "  -b 'lastCity=101210100; __zp_seo_uuid__=c127a66a-c32b-48c8-9922-38e68f276ceb; __l=r=https%3A%2F%2Fwww.google.com%2F&l=%2F&s=1; __g=-; Hm_lvt_194df3105ad7148dcf2b98a91b5e727a=1752227729; HMACCOUNT=E12FA8317F1FBEC2; wt2=DcZwnO_EigAmnmKo9ncVkLjm_VmGSQbYrNCtyZSlL6OQAcvq5C35SkpTxRDYFH8U7RrhTb80BENIxGag1RXDjHw~~; wbg=0; zp_at=p2KdHC6P5beWE8bSoHrWbW1ap7pNQcti2oo78rbNc6M~; ab_guid=c71d5784-aec0-4eb6-adea-9c538b7e331b; Hm_lpvt_194df3105ad7148dcf2b98a91b5e727a=1752230985; bst=V2Qt0mEOf-21lgXdJszRQdKC2w7DrTzQ~~|Qt0mEOf-21lgXdJszRQdKC2w7DvSzQ~~; __c=1752227729; __a=78645062.1752227729..1752227729.13.1.13.13; __zp_stoken__=771dfOTbDlsK9wpvCtD0vDwkJCQAwIDA2Kio4OSIyPDw5Njw%2BPjk2NBwwKcO7wrzCsDZJW8ONJzkiNjw1OTk4PDw6EjYwxLrCsDY5KcKRwrnCvTlMVcOABMK%2Fwr0RPcK5B8O0wr0EwoPCsxFowrkjJCzCvzAwOz3DgcK3wpDCusOBwr7CkMK9H8K%2Bwp3CvTAzPWUqNA4AX1k0M0hKVwJFVE1hWFELQktLJT0wNjk9wrfDvSw3CQ8PBgYJDw8GBgYMDAoKBgwMCQkDDQ0AAC48wpXCsMO8wo9ZwpDDosSWwpDCrsOqQ8KXwpLCm0nDtFPCrcK0w7vCtcKpwrvCtlHCo0rCr1vCiF%2FCocK1wpBkV15uRk97wrZvV8K%2FV2PCs1bDgWkKWwIEETQLXF3DgA%3D%3D' \\\n" +
                "  -H 'priority: u=1, i' \\\n" +
                "  -H 'referer: https://www.zhipin.com/web/geek/jobs?city=101210100' \\\n" +
                "  -H 'sec-ch-ua: \"Not)A;Brand\";v=\"8\", \"Chromium\";v=\"138\", \"Google Chrome\";v=\"138\"' \\\n" +
                "  -H 'sec-ch-ua-mobile: ?0' \\\n" +
                "  -H 'sec-ch-ua-platform: \"macOS\"' \\\n" +
                "  -H 'sec-fetch-dest: empty' \\\n" +
                "  -H 'sec-fetch-mode: cors' \\\n" +
                "  -H 'sec-fetch-site: same-origin' \\\n" +
                "  -H 'token: KhReS6dNmtMj1us' \\\n" +
                "  -H 'traceid: F-71e5a1svdUstoQK9' \\\n" +
                "  -H 'user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36' \\\n" +
                "  -H 'x-requested-with: XMLHttpRequest' \\\n" +
                "  -H 'zp_token: V2Qt0mEOf-21lgXdJszRQdKC2w7DrTzQ~~|Qt0mEOf-21lgXdJszRQdKC2w7DvSzQ~~'";
        SocketHttpResponse socketHttpResponse = sendCurlReceive("www.zhipin.com", 443, curl);
        System.out.println(socketHttpResponse);
    }

}


interface SocketHttpResponse {
    /**
     * 获取请求头
     *
     * @return
     */
    String getHeader();

    /**
     * 设置请求头
     *
     * @param header
     */
    void setHeader(String header);

    /**
     * 获取状态
     *
     * @return
     */
    Integer getHttpStatus();

    /**
     * 设置状态
     *
     * @param status
     */
    void setHttpStatus(Integer status);

    /**
     * 设置返回的body
     *
     * @return
     */
    String getBody();

    /**
     * 设置body
     *
     * @param body
     */
    void setBody(String body);
}

@Data
class DefaultSocketHttpResponse implements SocketHttpResponse {
    private String header;
    private Integer httpStatus;
    private String body;

}
